//noinspection JSAnnotator
/**
 * Created by worry on 2016/12/13.
 */
/**
 * 设置cookie
 * @param name
 * @param value
 */
function setCookie(name, value)
{
    var cookie = document.cookie;
    var expires=new Date();
    expires.setTime(expires.getTime()+(86400*365));
    document.cookie = name+ "=" + encodeURI(value)+"; expires="+expires.toGMTString()+"; path=/";
}
/**
 * 获取cookie
 * @param name
 * @returns {Array|{index: number, input: string}|string}
 */
function getCookie(name)
{
    var cookie = document.cookie;
    var res = cookie.match(eval("/"+name+"=([a-zA-Z0-9]*);|"+name+"=(\\w*)$/ig"));
    if(res){
        res = res[0].split('=')[1];
        res = res.indexOf(';') > 0 ? res.substring(0, res.indexOf(';')) : res;
    }
    return res || '';
}
/**
 * 删除cookie
 * @param name
 */
function delCookie(name)
{
    var date=new Date();
    //将date设置为过去的时间
    date.setTime(date.getTime()-10000);
    //将userId这个cookie删除
    document.cookie = name+'=000; expires='+date.toGMTString();
}

/**
 * 获取token
 */
function setToken()
{
    var token = '';
    $.ajax({
        url:ThinkPHP.U('Admin/Public/token'),
        async:false,
        dataType:'json',
        success: function(resp){
            if(resp.status == true){
                token = resp.data;
                setCookie('token', token);
            }
        }
    });
    return token;
}
/**
 * ckeditor 更新值
 * @constructor
 */
function CKupdate() {
    if(typeof CKEDITOR != "undefined") {
        for (var instance in CKEDITOR.instances)
            CKEDITOR.instances[instance].updateElement();
    }

}
/**
 * 设置token
 */
function getToken()
{
    var token = getCookie('token');
    if(!token){
        token = setToken();
    }
    $('input[name="token"]').val(token);
    return token;
}
/**
 * 重设Token
 * @returns {*}
 */
function resetToken()
{
    var token = setToken();
    return token;
}

function changesearch(obj)
{
    if($(obj).parents('form').length > 0){
        var form = $($(obj).parents('form')[0]);
        form.submit();
    }
}

function search(obj)
{
    if($(obj).parents('form').length > 0){

        var query = $(obj).parents('form:eq(0)').serialize();
        console.log(ThinkPHP);return;
        location.href(ThinkPHP.U(ThinkPHP.MODEL, query));
    }
}

/**
 * 通用上传成功回调函数
 * @param resp
 * @param options
 */
function uploadSuccessHandle(resp, options)
{
    if(resp.data.url){
        var imageUrl = resp.data.url;
        $(options.input).length && $(options.input).val(imageUrl);
        $(options.preview).length && $(options.preview).attr('src', imageUrl);
    }
}

function QiniuUploadSuccessHandle(resp, options)
{
    if(resp.key) {
        var imageUrl = QINIU.domain + resp.key;
        $(options.input).val(imageUrl);
        $(options.preview).attr('src', imageUrl);
    }
}

function showUploadFiles(ext, options)
{
    $.get(ThinkPHP.U('Admin/Public/uploadFiles', 'ext='+ext), function(html){
        layer.open({
            type:1,
            content:html,
            area:['500px', '400px'],
            btn:['确认', '取消'],
            btn1:function(index){
                if($('.layui-layer-content .upload-file li.active').length == 1 && options){
                    var url = $('.layui-layer-content .upload-file li.active').attr('data-url');
                    if(options.success) {
                        options.success(url);
                    } else {
                        $(options.input).val(url);
                        $(options.preview).attr('src', url);
                    }
                    layer.close(index);
                } else {
                    layer.msg('请选择文件');
                }
            }
        });
        $('.upload-file li').click(function(){
            if($(this).hasClass('active')) {
                $(this).addClass('active');
            } else {
                $('.upload-file li').removeClass('active');
                $(this).addClass('active');
            }
        });
    });
}

/**
 * 通用上传错误回调
 * @param resp
 * @param options
 */
function uploadErrorHandle(resp, options)
{
    $(options.input).length && $(options.input).val('');
    $(options.preview).length && $(options.preview).attr('src', '');
    layer.alert(resp.msg);
}

function qiniuUpload(options)
{
    var form = $('<form method="post" action="'+options.url+'" style="display:none;" enctype="multipart/form-data">\
            <input name="key" value="site/'+sha1(Date.now().toString())+'"/>\
            <input name="token" type="hidden" value="'+QINIU.token+'">\
            <input name="file" type="file" />\
        </form>'),
        file = $('input[type=file]', form);
    form.appendTo('body');
    $(file).off().on('change', function () {
        var fileName = $(this).val() ? $(this).val().toLowerCase() : '';
        try {
            //检查文件类型
            if (options.type) {
                var status = false;
                $(options.type).each(function () {
                    var reg = new RegExp(".*\."+this.toLowerCase()+"$");
                    if (fileName.match(reg)) {
                        status = true;
                        return true;
                    }
                });
                if (status == false) {
                    throw "该文件不允许上传";
                }
            }
            //提交表单
            $(form).ajaxSubmit({
                dataType: 'json',
                error: function (xhr) {
                    $(form).remove();
                    console.log(xhr.state);
                    layer.msg('网络异常');
                },
                success: function (resp) {
                    options.success(resp, options);
                    $(form).remove();
                }
            });
        } catch (e) {
            $(form).remove();
            layer.msg(e);
        }
    });
    $(file).trigger('click');
}

/**
 * 通用上传函数
 * @param options 上传参数 {url:'服务器地址', type:[允许上传类型], preview:'预览图片DOM', input:'返回图片路径表单标签', success:function(){回调代码},error:function(){错误回调代码}, name:'上传name'}
 */
function upload(options)
{
    var form = $('<form method="post" action="'+options.url+'" enctype="multipart/form-data">\
                <input name="token" type="hidden" value="'+options.token+'">\
                <input name="file" type="file" />\
            </form>'),
        file = $('input[type=file]', form);
    form.appendTo('body');
    $(file).off().on('change', function () {
        var fileName = $(this).val() ? $(this).val().toLowerCase() : '';
        try {
            //检查文件类型
            if (options.type) {
                var status = false;
                $(options.type).each(function () {
                    var reg = new RegExp(".*\."+this.toLowerCase()+"$");
                    if (fileName.match(reg)) {
                        status = true;
                        return true;
                    }
                });
                if (status == false) {
                    throw "该文件不允许上传";
                }
            }
            //提交表单
            $(form).ajaxSubmit({
                dataType: 'json',
                error: function (xhr) {
                    $(form).remove();
                    layer.msg('网络异常')
                },
                success: function (resp) {
                    if (resp.status == true) {
                        options.success(resp, options);
                    } else {
                        options.error(resp);
                    }
                    $(form).remove();
                }
            });
        } catch (e) {
            $(form).remove();
            layer.msg(e);
        }
    });
    $(file).trigger('click');
}
/**
 * wang editor 初始化
 * @param id
 */
function wangInit(id)
{
    var editor = new wangEditor('content');
    editor.config.customUpload = true;
    editor.config.customUploadInit = function(){
        $('#'+editor.customUploadBtnId).click(function(){
            var options = {
                name:'uploadimage',
                url:'http://upload.qiniu.com',
                type:['png', 'jpg','jpeg', 'gif'],
                preview:'.preview-upload',
                token:QINIU.token,
                input:'input[name="slide_image"]',
                success:function(resp){
                    var originalName = editor.uploadImgOriginalName || '';
                    editor.command(null, 'insertHtml', '<img src="' + QINIU.domain + resp.key + '" alt="' + originalName + '" style="max-width:100%;height:auto;display:block;"/>');
                },
                error:function(resp){
                    uploadErrorHandle(resp, this);
                }
            };
            qiniuUpload(options);
        });
    };
    editor.create();
}
/**
 * CK Editor 初始化
 * @param id
 */
function CKInit(id)
{
    var editor = CKEDITOR.replace(id,{"extraPlugins":"filebrowser,image,imagepaste,filetools"});
    editor.on( 'instanceReady', function(e) {
        //editor.resize(200, 200);

        editor.addCommand("imageAlignLeft", {
            exec : function( editor )
            {
                var imgs = editor.document.getElementsByTag('img');
                for (var i = 0; i < imgs.$.length; i++) {
                    var img = imgs.$[i];
                    img.style.width = 'auto';
                    img.style.height = 'auto';
                    img.style.display = 'block';
                    img.style.margin = '0 auto 0 0';
                    img.style.maxWidth = '100%';
                }
            }
        });
        editor.addCommand("imageAlignRight", {
            exec : function( editor )
            {
                var imgs = editor.document.getElementsByTag('img');
                for (var i = 0; i < imgs.$.length; i++) {
                    var img = imgs.$[i];
                    img.style.width = 'auto';
                    img.style.height = 'auto';
                    img.style.display = 'block';
                    img.style.margin = '0 0 0 auto';
                    img.style.maxWidth = '100%';
                }
            }
        });
        editor.addCommand("imageAlignCenter", {
            exec : function( editor )
            {
                var imgs = editor.document.getElementsByTag('img');
                for (var i = 0; i < imgs.$.length; i++) {
                    var img = imgs.$[i];
                    img.style.width = 'auto';
                    img.style.height = 'auto';
                    img.style.display = 'block';
                    img.style.margin = '0 auto';
                    img.style.maxWidth = '100%';
                }
            }
        });




        editor.contextMenu.addListener( function( element, selection ) {
            return {
                imageAlignLeft : CKEDITOR.TRISTATE_OFF ,
                imageAlignRight : CKEDITOR.TRISTATE_OFF ,
                imageAlignCenter : CKEDITOR.TRISTATE_OFF ,
            };
        });

        editor.addMenuItems({
            imageAlignLeft : {
                label : "图像居左",
                command : 'imageAlignLeft',
                group : 'image',
                order : 1
            },
            imageAlignRight : {
                label : "图像居右",
                command : 'imageAlignRight',
                group : 'image',
                order : 2
            },
            imageAlignCenter : {
                label : "图像居中",
                command : 'imageAlignCenter',
                group : 'image',
                order : 3
            },
        });
    });
}

var editorConfig = {
        menus:[
            "source",
            "|",
            "bold",
            "underline",
            "italic",
            "strikethrough",
            "eraser",
            "forecolor",
            "bgcolor",
            "|",
            "quote",
            "fontfamily",
            "customFontSize",
            "head",
            "unorderlist",
            "orderlist",
            "alignleft",
            "aligncenter",
            "alignright",
            "|",
            "link",
            "unlink",
            "table",
            "emotion",
            "|",
            "img",
            "showUploadMenu",
            "video",
            "location",
            "insertcode",
            "|",
            "undo",
            "redo",
            "fullscreen"
        ],
        fontsizes:[
            // 格式：'value': 'title'
            '10px', '13px','16px','18px','20px','22px','24px','26px','28px', '32px', '34px','48px'
        ],
    };

+function($){
    $('.show-upload').on('click', function(){
       showUploadFiles($(this).attr('data-ext'), {input:$(this).attr('data-input'), preview:$(this).attr('data-preview')});
    });


    $('.ajax-click').on('click', function(){
       var url = $(this).attr('data-url');
       if(url){
           $.getJSON(url, function(resp, status, xhr){
               if(resp.status === true){
                   layer.msg(resp.msg);
                   if(resp.redirectUrl){
                       location.href = resp.redirectUrl;
                   }

               } else{
                   resp.msg ? layer.alert(resp.msg) : layer.open({content:xhr.responseText});
               }
           })
       }
    });
    //排序
    $('.sort-list').click(function(){
        var load = layer.load();
        var param = [];
        $('.sort-input').each(function(){
            var id = $(this).attr('pk');
            var sort = $(this).val();
            if(id){
                param.push({id:id, sort:sort});
            }
        });
        var url = location.href;
        $.ajax({
            url:url,
            type:'post',
            dataType:'json',
            data:{sort:param},
            error:function(xhr){
                layer.close(load);
                layer.open({area:['500px', '400px'],content:xhr.responseText});
            },
            success:function(resp){
                layer.close(load);
                if(resp.status === true){
                    location.reload();
                }else{
                    layer.msg(resp.msg);
                }
            }
        })
    });
    $('form').submit(function(){
        var form = this;
        CKupdate();
        if($(form).attr('data-no-submit') == 1) {
            return false;
        }
        if($(form).hasClass('ajax-submit')){
            var load = layer.load();
            var beforeCall = $(form).attr('before');
            var callback = $(form).attr('callback');
            if(self[beforeCall]){
                if(self[beforeCall]() == false){
                    return false;
                }
            }
            $(form).ajaxSubmit({
                dataType:'json',
                error:function(xhr){
                    layer.close(load);
                    layer.open({area:['500px', '400px'],content:xhr.responseText});
                },
                success:function(resp){
                    layer.close(load);

                    if(self[callback]){
                        self[callback](resp);
                        return false;
                    }
                    var returnUrl = $(form).attr('return-url');
                    if(resp.status === true){
                        $(form)[0].reset();
                        layer.msg(resp.msg);
                        if(returnUrl){
                            setTimout(function(){
                                location.href = returnUrl;
                            }, 1000)
                        } else if(resp.redirectUrl){
                            location.href = resp.redirectUrl;
                        }

                    }else{
                        if(resp.errbtn){
                            var errobj = $(form).find('[name="'+resp.errbtn+'"]');
                            layer.tips(resp.msg, errobj);
                            errobj.focus();
                        } else {
                            layer.msg(resp.msg);
                        }
                    }
                }
            });
        } else {
            return true;
        }
        return false;
    });


	$(".win-homepage").click(function(){ 
        if(document.all){
        document.body.style.behavior = 'url(#default#homepage)'; 
        document.body.setHomePage(document.URL); 
        }else{alert("设置首页失败，请手动设置！");} 
	});
	$(".win-favorite").click(function(){
		var sURL=document.URL; 
		var sTitle=document.title; 
		try {window.external.addFavorite(sURL, sTitle);} 
		catch(e){ 
			try{window.sidebar.addPanel(sTitle, sURL, "");} 
			catch(e){alert("加入收藏失败，请使用Ctrl+D进行添加");} 
		}
	});
	$(".win-forward").click(function(){
		window.history.forward(1);
	});
	$(".win-back").click(function(){
		window.history.back(-1);
	});
	$(".win-backtop").click(function(){$('body,html').animate({scrollTop:0},1000);return false;});
	$(".win-refresh").click(function(){
		window.location.reload();
	});
	$(".win-print").click(function(){
		window.print();
	});
	$(".win-close").click(function(){
		window.close();
	});
	$('.checkall').click(function(){
		var e=$(this);
		var name=e.attr("name");
		var checkfor=e.attr("checkfor");
		var type;
		if (checkfor!='' && checkfor!=null && checkfor!=undefined){
			type=e.closest('form').find("input[name='"+checkfor+"']");
		}else{
			type=e.closest('form').find("input[type='checkbox']");
		};
		if (name=="checkall"){
			$(type).each(function(index, element){
				element.checked=true;
			});
			e.attr("name","ok");
		}else{
			$(type).each(function(index, element){
				element.checked=false;
			});
			e.attr("name","checkall");
		}	
	});
	$('.dropdown-toggle').click(function(){
		$(this).closest('.button-group, .drop').addClass("open");
	});
	 $(document).bind("click",function(e){
		 if($(e.target).closest(".button-group.open, .drop.open").length == 0){
			 $(".button-group, .drop").removeClass("open");
		 }
	});
	$checkplaceholder=function(){
		var input = document.createElement('input');
		return 'placeholder' in input;
	};
	if(!$checkplaceholder()){
		$("textarea[placeholder], input[placeholder]").each(function(index, element){
			var content=false;
			if($(this).val().length ===0 || $(this).val()==$(this).attr("placeholder")){content=true};
			if(content){
				$(element).val($(element).attr("placeholder"));
				$(element).css("color","rgb(169,169,169)");
				$(element).data("pintuerholder",$(element).css("color"));
				$(element).focus(function(){$hideplaceholder($(this));});
				$(element).blur(function(){$showplaceholder($(this));});
			}
		})
	};
	$showplaceholder=function(element){
		if( ($(element).val().length ===0 || $(element).val()==$(element).attr("placeholder")) && $(element).attr("type")!="password"){
			$(element).val($(element).attr("placeholder"));
			$(element).data("pintuerholder",$(element).css("color"));
			$(element).css("color","rgb(169,169,169)");
		}
	};
	var $hideplaceholder=function(element){
		if($(element).data("pintuerholder")){
			$(element).val("");
			$(element).css("color", $(element).data("pintuerholder"));		
			$(element).removeData("pintuerholder");
		}
	};
	$('textarea, input, select').blur(function(){
		var e=$(this);
		if(e.attr("data-validate")){
			e.closest('.field').find(".input-help").remove();
			var $checkdata=e.attr("data-validate").split(',');
			var $checkvalue=e.val();
			var $checkstate=true;
			var $checktext="";
			if(e.attr("placeholder")==$checkvalue){$checkvalue="";}
			if($checkvalue!="" || e.attr("data-validate").indexOf("required")>=0){
				for(var i=0;i<$checkdata.length;i++){
					var $checktype=$checkdata[i].split(':');
					if(! $pintuercheck(e,$checktype[0],$checkvalue)){
						$checkstate=false;
						$checktext=$checktext+"<li>"+$checktype[1]+"</li>";
					}
				}
			};
			if($checkstate){
				e.closest('.form-group').removeClass("check-error");
				e.parent().find(".input-help").remove();
				e.closest('.form-group').addClass("check-success");
			}else{
				e.closest('.form-group').removeClass("check-success");
				e.closest('.form-group').addClass("check-error");
				e.closest('.field').append('<div class="input-help"><ul>'+$checktext+'</ul></div>');
			}
		}
	});
	$pintuercheck=function(element,type,value){
		$pintu=value.replace(/(^\s*)|(\s*$)/g, "");
		switch(type){
			case "required":return /[^(^\s*)|(\s*$)]/.test($pintu);break;
			case "chinese":return /^[\u0391-\uFFE5]+$/.test($pintu);break;
			case "number":return /^\d+$/.test($pintu);break;
			case "integer":return /^[-\+]?\d+$/.test($pintu);break;
			case "plusinteger":return /^[+]?\d+$/.test($pintu);break;
			case "double":return /^[-\+]?\d+(\.\d+)?$/.test($pintu);break;
			case "plusdouble":return /^[+]?\d+(\.\d+)?$/.test($pintu);break;
			case "english":return /^[A-Za-z]+$/.test($pintu);break;
			case "username":return /^[a-z]\w{3,}$/i.test($pintu);break;
			case "mobile":return /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$|170\d{8}?$|147\d{8}?$/.test($pintu);break;
			case "phone":return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/.test($pintu);break;
			case "tel":return /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$|170\d{8}?$|147\d{8}?$/.test($pintu) || /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/.test($pintu);break;
			case "email":return /^[^@]+@[^@]+\.[^@]+$/.test($pintu);break;
			case "url":return /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($pintu);break;
			case "ip":return /^[\d\.]{7,15}$/.test($pintu);break;
			case "qq":return /^[1-9]\d{4,10}$/.test($pintu);break;
			case "currency":return /^\d+(\.\d+)?$/.test($pintu);break;
			case "zip":return /^[1-9]\d{5}$/.test($pintu);break;
			case "radio":
				var radio=element.closest('form').find('input[name="'+element.attr("name")+'"]:checked').length;
				return eval(radio==1);
				break;
			default:
				var $test=type.split('#');
				if($test.length>1){
					switch($test[0]){
						case "compare":
							return eval(Number($pintu)+$test[1]);
							break;
						case "regexp":
							return new RegExp($test[1],"gi").test($pintu);
							break;
						case "length":
							var $length;
							if(element.attr("type")=="checkbox"){
								$length=element.closest('form').find('input[name="'+element.attr("name")+'"]:checked').length;
							}else{
								$length=$pintu.replace(/[\u4e00-\u9fa5]/g,"***").length;
							}
							return eval($length+$test[1]);
							break;
						case "ajax":							
							var $getdata;
							var $url=$test[1]+$pintu;							
							$.ajaxSetup({async:false});
							$.getJSON($url,function(data){	
								//alert(data.getdata);							
								$getdata=data.getdata;								
							});
							if($getdata=="true"){return true;}
							break;
						case "repeat":
							return $pintu==jQuery('input[name="'+$test[1]+'"]').eq(0).val();
							break;
						default:return true;break;
					}
					break;
				}else{
					return true;
				}
		}
	};

	//pintuer.js
	$('form').submit(function(){
		$(this).find('input[data-validate],textarea[data-validate],select[data-validate]').trigger("blur");
		$(this).find('input[placeholder],textarea[placeholder]').each(function(){$hideplaceholder($(this));});
		var numError = $(this).find('.check-error').length;
		if(numError){
			$(this).find('.check-error').first().find('input[data-validate],textarea[data-validate],select[data-validate]').first().focus().select();
			return false;
		}
	});
	$('.form-reset').click(function(){
		$(this).closest('form').find(".input-help").remove();
		$(this).closest('form').find('.form-submit').removeAttr('disabled');
		$(this).closest('form').find('.form-group').removeClass("check-error");
		$(this).closest('form').find('.form-group').removeClass("check-success");
	});
	$('.tab .tab-nav li').each(function(){
		var e=$(this);
		var trigger=e.closest('.tab').attr("data-toggle");
		if (trigger=="hover"){
			e.mouseover(function(){
				$showtabs(e);
			});
			e.click(function(){
				return false;
			});
		}else{
			e.click(function(){
				$showtabs(e);
				return false;
			});
		}
	});
	$showtabs=function(e){
		var detail=e.children("a").attr("href");
		e.closest('.tab .tab-nav').find("li").removeClass("active");
		e.closest('.tab').find(".tab-body .tab-panel").removeClass("active");
		e.addClass("active");
		$(detail).addClass("active");
	};
	$('.dialogs').each(function(){
		var e=$(this);
		var trigger=e.attr("data-toggle");
		if (trigger=="hover"){
			e.mouseover(function(){
				$showdialogs(e);
			});
		}else if(trigger=="click"){
			e.click(function(){
				$showdialogs(e);
			});
		}
	});
	$showdialogs=function(e){
		var trigger=e.attr("data-toggle");
		var getid=e.attr("data-target");
		var data=e.attr("data-url");
		var mask=e.attr("data-mask");
		var width=e.attr("data-width");
		var detail="";
		var masklayout=$('<div class="dialog-mask"></div>');
		if(width==null){width="80%";}
		
		if (mask=="1"){
			$("body").append(masklayout);
		}
		detail='<div class="dialog-win" style="position:fixed;width:'+width+';z-index:11;">';
		if(getid!=null){detail=detail+$(getid).html();}
		if(data!=null){detail=detail+$.ajax({url:data,async:false}).responseText;}
		//alert(detail);
		detail=detail+'</div>';
		
		var win=$(detail);
		win.find(".dialog").addClass("open");
		$("body").append(win);
		var x=parseInt($(window).width()-win.outerWidth())/2;
		var y=parseInt($(window).height()-win.outerHeight())/2;
		if (y<=10){y="10"}
		win.css({"left":x,"top":y});
		win.find(".dialog-close,.close").each(function(){
			$(this).click(function(){
				win.remove();
				$('.dialog-mask').remove();
			});
		});
		masklayout.click(function(){
			win.remove();
			$(this).remove();
		});
	};
	$('.tips').each(function(){
		var e=$(this);
		var title=e.attr("title");
		var trigger=e.attr("data-toggle");
		e.attr("title","");
		if (trigger=="" || trigger==null){trigger="hover";}
		if (trigger=="hover"){
			e.mouseover(function(){
				$showtips(e,title);
			});
		}else if(trigger=="click"){
			e.click(function(){
				$showtips(e,title);
			});
		}else if(trigger=="show"){
			e.ready(function(){
				$showtips(e,title);
			});
		}
	});
	$showtips=function(e,title){
		var trigger=e.attr("data-toggle");
		var place=e.attr("data-place");
		var width=e.attr("data-width");
		var css=e.attr("data-style");
		var image=e.attr("data-image");
		var content=e.attr("content");
		var getid=e.attr("data-target");
		var data=e.attr("data-url");
		var x=0;
		var y=0;
		var html="";
		var detail="";
		
		if(image!=null){detail=detail+'<img class="image" src="'+image+'" />';}
		if(content!=null){detail=detail+'<p class="tip-body">'+content+'</p>';}
		if(getid!=null){detail=detail+$(getid).html();}
		if(data!=null){detail=detail+$.ajax({url:data,async:false}).responseText;}
		if(title!=null && title!=""){
			if(detail!=null && detail!=""){detail='<p class="tip-title"><strong>'+title+'</strong></p>'+detail;}else{detail='<p class="tip-line">'+title+'</p>';}
		}
		detail='<div class="tip">'+detail+'</div>';
		html=$(detail);

		$("body").append( html );
		if(width!=null){
			html.css("width",width);
		}
		if(place=="" || place==null){place="top";}
		if(place=="left"){
			x=e.offset().left - html.outerWidth()-5;
			y=e.offset().top - html.outerHeight()/2 + e.outerHeight()/2;
		}else if(place=="top"){
			x=e.offset().left - html.outerWidth()/2 + e.outerWidth()/2;
			y=e.offset().top - html.outerHeight()-5;
		}else if(place=="right"){
			x=e.offset().left + e.outerWidth()+5;
			y=e.offset().top - html.outerHeight()/2 + e.outerHeight()/2;
		}else if(place=="bottom"){
			x=e.offset().left - html.outerWidth()/2 + e.outerWidth()/2;
			y=e.offset().top + e.outerHeight()+5;
		}
		if (css!=""){html.addClass(css);}
		html.css({"left":x+"px","top":y+"px","position":"absolute"});
		if (trigger=="hover" || trigger=="click" || trigger==null){
			e.mouseout(function(){html.remove();e.attr("title",title)});
		}
	};
	$('.alert .close').each(function(){
		$(this).click(function(){
			$(this).closest('.alert').remove();
		});
	});
	$('.radio label').each(function(){
		var e=$(this);
		e.click(function(){
			e.closest('.radio').find("label").removeClass("active");
			e.addClass("active");
		});
	});
	$('.checkbox label').each(function(){
		var e=$(this);
		e.click(function(){
			if(e.find('input').is(':checked')){
				e.addClass("active");
			}else{
				e.removeClass("active");
			};
		});
	});
	$('.collapse .panel-head').each(function(){
		var e=$(this);
		e.click(function(){
			e.closest('.collapse').find(".panel").removeClass("active");
			e.closest('.panel').addClass("active");
		});
	});
	$('.icon-navicon').each(function(){
		var e=$(this);
		var target=e.attr("data-target");
		e.click(function(){
			$(target).toggleClass("nav-navicon");
		});
	});
	$('.banner').each(function(){
		var e=$(this);
		var pointer=e.attr("data-pointer");
		var interval=e.attr("data-interval");
		var style=e.attr("data-style");
		var items=e.attr("data-item");
		var items_s=e.attr("data-small");
		var items_m=e.attr("data-middle");
		var items_b=e.attr("data-big");
		var num=e.find(".carousel .item").length;
		var win=$(window).width();
		var i=1;

		if(interval==null){interval=5};
		if(items==null || items<1){items=1};
		if(items_s!=null && win>760){items=items_s};
		if(items_m!=null && win>1000){items=items_m};
		if(items_b!=null && win>1200){items=items_b};

		var itemWidth=Math.ceil(e.outerWidth()/items);
		var page=Math.ceil(num/items);
		e.find(".carousel .item").css("width",itemWidth+ "px");
		e.find(".carousel").css("width",itemWidth*num + "px");
		
		var carousel=function(){
			i++;
			if(i>page){i=1;}
			$showbanner(e,i,items,num);
		};
		var play=setInterval(carousel,interval*600);
		
		e.mouseover(function(){clearInterval(play);});
		e.mouseout(function(){play=setInterval(carousel,interval*600);});
		
		if(pointer!=0 && page>1){
			var point='<ul class="pointer"><li value="1" class="active"></li>';
			for (var j=1;j<page;j++){
				point=point+' <li value="'+(j+1)+'"></li>';
			};
			point=point+'</ul>';
			var pager=$(point);
			if(style!=null){pager.addClass(style);};
			e.append(pager);
			pager.css("left",e.outerWidth()*0.5 - pager.outerWidth()*0.5+"px");
			pager.find("li").click(function(){
				$showbanner(e,$(this).val(),items,num);
			});
			var lefter=$('<div class="pager-prev icon-angle-left"></div>');
			var righter=$('<div class="pager-next icon-angle-right"></div>');
			if(style!=null){lefter.addClass(style);righter.addClass(style);};
			e.append(lefter);
			e.append(righter);
			
			lefter.click(function(){
				i--;
				if(i<1){i=page;}
				$showbanner(e,i,items,num);
			});
			righter.click(function(){
				i++;
				if(i>page){i=1;}
				$showbanner(e,i,items,num);
			});
		};
	});	
	$showbanner=function(e,i,items,num){
		var after=0,leftx=0;
		leftx = - Math.ceil(e.outerWidth()/items)*(items)*(i-1);
		if(i*items > num){after=i*items-num;leftx= - Math.ceil(e.outerWidth()/items)*(num-items);};
		e.find(".carousel").stop(true, true).animate({"left":leftx+"px"},800);
		e.find(".pointer li").removeClass("active");
		e.find(".pointer li").eq(i-1).addClass("active");
	};
	$(".spy a").each(function(){
		var e=$(this);
		var t=e.closest(".spy");
		var target=t.attr("data-target");
		var top=t.attr("data-offset-spy");
		var thistarget="";
		var thistop="";
		if(top==null){top=0;};
		if(target==null){thistarget=$(window);}else{thistarget=$(target);};
		
		thistarget.bind("scroll",function(){
			if(target==null){
				thistop=$(e.attr("href")).offset().top - $(window).scrollTop() - parseInt(top);	
			}else{
				thistop=$(e.attr("href")).offset().top - thistarget.offset().top - parseInt(top);
			};
	
			if(thistop<0){
				t.find('li').removeClass("active");
				e.parents('li').addClass("active");
			};

		});
	});
	$(".fixed").each(function(){
		var e=$(this);
		var style=e.attr("data-style");
		var top=e.attr("data-offset-fixed");
		if(top==null){top=e.offset().top;}else{top=e.offset().top - parseInt(top);};
		if(style==null){style="fixed-top";};
		
		$(window).bind("scroll",function(){
			var thistop=top - $(window).scrollTop();
			if(style=="fixed-top" && thistop<0){
				e.addClass("fixed-top");
			}else{
				e.removeClass("fixed-top");
			};
			
			var thisbottom=top - $(window).scrollTop()-$(window).height();
			if(style=="fixed-bottom" && thisbottom>0){
				e.addClass("fixed-bottom");
			}else{
				e.removeClass("fixed-bottom");
			};
		});

	});
}(jQuery);
